package com.bdqn.servlet;

import com.bdqn.pojo.SysUser;
import com.bdqn.service.SysUserService;
import com.bdqn.service.SysUserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 系统登录Servlet
 *
 * @author LILIBO
 * @since 2021-09-15
 */
@WebServlet("/user")
public class SysUserServlet extends HttpServlet {

    private SysUserService sysUserService = new SysUserServiceImpl();

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        String opr = request.getParameter("opr");

        switch (opr) {
            case "login":
                String account = request.getParameter("account");
                String password = request.getParameter("password");
                SysUser sysUser = sysUserService.getSysUserByAccountAndPassword(account, password);
                if (sysUser != null) {
                    request.getSession().setAttribute("USER_SESSION", sysUser);
                    request.getRequestDispatcher("jsp/frame.jsp").forward(request, response);
                } else {
                    request.setAttribute("error", "用户名或密码错误");
                    request.getRequestDispatcher("jsp/login.jsp").forward(request, response);
                }
                break;
            case "logout":
                request.getSession().removeAttribute("USER_SESSION");
                response.sendRedirect("jsp/login.jsp");
                break;
        }
    }

}
